package com.example.meeting.socket;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.meeting.socket.pojo.MessageType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

import static org.apache.logging.log4j.message.MapMessage.MapFormat.JSON;

//@ServerEndpoint("/websocket/{id}")
@Component
@Slf4j
public class Websocket {
    private Integer id;
    private String uuid;
    private Integer UserId = -1;

    private static final ConcurrentHashMap<Integer, Session> sessionPool = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "id") Integer id) {
        this.id = id;
        this.uuid = IdUtil.simpleUUID();
        sessionPool.put(id, session);
        log.debug("有新的客户端连接，连接总数："+sessionPool.size());
    }

    @OnClose
    public void onClose() {
        if(this.uuid != null) {
            sessionPool.remove(this.uuid);
            log.debug("有新的客户端断开连接，连接总数："+sessionPool.size());
        }
    }

    @OnMessage
    public void onMessage(String message,Session session) {
        log.debug("收到客户端消息："+message);
        if(ObjectUtil.isEmpty(message)) return;

        JSONObject input = JSONUtil.parseObj(message);
        String code = input.getStr("code");
        MessageType messageType;
        try {
            messageType = Enum.valueOf(MessageType.class, code);
        } catch (Exception e) {
            log.error("消息类型错误: ",e.getMessage());
            return;
        }
        switch (messageType) {
            case PING:
                //send(session, JSONUtil.toJsonStr(new JSONObject().put("code", MessageType.PONG.name())));
                break;
            case ENTER:
                this.UserId = input.getInt("userId");
                break;
            default:
                break;
        }
    }
}
